/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.com.sysvent.view;

import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class ClienteView extends JPanel {
    
    public ClienteView() {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("systokPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Cliente c");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        jPanel1 = new javax.swing.JPanel();
        detailScrollPane = new javax.swing.JScrollPane();
        detailTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        IngresarCliente_Boton = new javax.swing.JButton();
        Guardar = new javax.swing.JButton();
        EliminarDir_Boton = new javax.swing.JButton();
        IngresarDir_Boton = new javax.swing.JButton();
        Actualizar = new javax.swing.JButton();
        EliminarCliente_Boton = new javax.swing.JButton();
        EditarCliente_Boton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        jPanel1.setBackground(new java.awt.Color(204, 204, 204));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Direccion del cliente"));

        detailScrollPane.setViewportView(detailTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(detailScrollPane)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(detailScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );

        jPanel2.setBackground(new java.awt.Color(204, 204, 204));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del cliente"));

        masterScrollPane.setViewportView(masterTable);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBackground(new java.awt.Color(204, 204, 204));

        IngresarCliente_Boton.setText("Ingresar Cliente");
        IngresarCliente_Boton.addActionListener(formListener);

        Guardar.setText("Guardar Datos");
        Guardar.addActionListener(formListener);

        EliminarDir_Boton.setText("Eliminar Direccion");
        EliminarDir_Boton.addActionListener(formListener);

        IngresarDir_Boton.setText("Ingresar Direccion");
        IngresarDir_Boton.addActionListener(formListener);

        Actualizar.setText("Actualizar Edicion");
        Actualizar.addActionListener(formListener);

        EliminarCliente_Boton.setText("Eliminar Cliente");
        EliminarCliente_Boton.addActionListener(formListener);

        EditarCliente_Boton.setText("Editar Cliente");
        EditarCliente_Boton.addActionListener(formListener);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(IngresarCliente_Boton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(EditarCliente_Boton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(EliminarCliente_Boton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(IngresarDir_Boton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Actualizar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Guardar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(EliminarDir_Boton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(10, 10, 10))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addComponent(IngresarCliente_Boton)
                .addGap(18, 18, 18)
                .addComponent(EditarCliente_Boton)
                .addGap(18, 18, 18)
                .addComponent(EliminarCliente_Boton)
                .addGap(95, 95, 95)
                .addComponent(IngresarDir_Boton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(EliminarDir_Boton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                .addComponent(Actualizar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Guardar)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(104, 104, 104))))
        );
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == IngresarCliente_Boton) {
                ClienteView.this.IngresarCliente_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == Guardar) {
                ClienteView.this.GuardarActionPerformed(evt);
            }
            else if (evt.getSource() == EliminarDir_Boton) {
                ClienteView.this.EliminarDir_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == IngresarDir_Boton) {
                ClienteView.this.IngresarDir_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == Actualizar) {
                ClienteView.this.ActualizarActionPerformed(evt);
            }
            else if (evt.getSource() == EliminarCliente_Boton) {
                ClienteView.this.EliminarCliente_BotonActionPerformed(evt);
            }
            else if (evt.getSource() == EditarCliente_Boton) {
                ClienteView.this.EditarCliente_BotonActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private void IngresarCliente_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IngresarCliente_BotonActionPerformed
        
        py.com.sysvent.bean.Cliente C = new py.com.sysvent.bean.Cliente();
        entityManager.persist(C);
        list.add(C);
        int row = list.size()-1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        ClienteEditView ce= new ClienteEditView(null,true);
        ce.setRegistroActual(C);//
        ce.setVisible(true);
        if (ce.isConfirmarCliente()){
       Guardar.doClick();//
        }else {//sino
        Actualizar.doClick(); }
    }//GEN-LAST:event_IngresarCliente_BotonActionPerformed

    private void GuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuardarActionPerformed
        try {
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
        } catch (RollbackException rex) {
            rex.printStackTrace();
            entityManager.getTransaction().begin();
            List<py.com.sysvent.bean.Cliente> merged = new ArrayList<py.com.sysvent.bean.Cliente>(list.size());
            for (py.com.sysvent.bean.Cliente C : list) {
                merged.add(entityManager.merge(C));
            }
            list.clear();
            list.addAll(merged);
        }
        JOptionPane.showMessageDialog(this, "Se ha guardado correctamente", "Aviso de Guardado", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_GuardarActionPerformed

    private void EliminarDir_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarDir_BotonActionPerformed
        int index = masterTable.getSelectedRow();
        py.com.sysvent.bean.Cliente C = list.get(masterTable.convertRowIndexToModel(index));
        Collection<py.com.sysvent.bean.ClienteDireccion> cs = C.getClienteDireccionList();
        int[] selected = detailTable.getSelectedRows();
        List<py.com.sysvent.bean.ClienteDireccion> toRemove = new ArrayList<py.com.sysvent.bean.ClienteDireccion>(selected.length);
        for (int idx = 0; idx < selected.length; idx++) {
            selected[idx] = detailTable.convertRowIndexToModel(selected[idx]);
            int count = 0;
            Iterator<py.com.sysvent.bean.ClienteDireccion> iter = cs.iterator();
            while (count++ < selected[idx]) {
                iter.next();
            }
            py.com.sysvent.bean.ClienteDireccion c = iter.next();
            toRemove.add(c);
            entityManager.remove(c);
        }
        cs.removeAll(toRemove);
        masterTable.clearSelection();
        masterTable.setRowSelectionInterval(index, index);
    }//GEN-LAST:event_EliminarDir_BotonActionPerformed

    private void IngresarDir_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IngresarDir_BotonActionPerformed
        int index = masterTable.getSelectedRow();
        py.com.sysvent.bean.Cliente C = list.get(masterTable.convertRowIndexToModel(index));
        Collection<py.com.sysvent.bean.ClienteDireccion> cs = C.getClienteDireccionList();
        if (cs == null) {
            cs = new LinkedList<py.com.sysvent.bean.ClienteDireccion>();
            C.setClienteDireccionList((List) cs);
        }
        py.com.sysvent.bean.ClienteDireccion c = new py.com.sysvent.bean.ClienteDireccion();
        entityManager.persist(c);
        c.setCodCliente(C);
        cs.add(c);
        masterTable.clearSelection();
        masterTable.setRowSelectionInterval(index, index);
        int row = cs.size() - 1;
        detailTable.setRowSelectionInterval(row, row);
        detailTable.scrollRectToVisible(detailTable.getCellRect(row, 0, true));
    }//GEN-LAST:event_IngresarDir_BotonActionPerformed

    private void ActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ActualizarActionPerformed
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        JOptionPane.showMessageDialog(this, "Se ha actualizado correctamente", "Aviso de Actualizacion", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_ActualizarActionPerformed

    private void EliminarCliente_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarCliente_BotonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        List<py.com.sysvent.bean.Cliente> toRemove = new ArrayList<py.com.sysvent.bean.Cliente>(selected.length);
        for (int idx = 0; idx < selected.length; idx++) {
            py.com.sysvent.bean.Cliente C = list.get(masterTable.convertRowIndexToModel(selected[idx]));
            toRemove.add(C);
            entityManager.remove(C);
        }
        list.removeAll(toRemove);
    }//GEN-LAST:event_EliminarCliente_BotonActionPerformed

    private void EditarCliente_BotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditarCliente_BotonActionPerformed

        ClienteEditView ce= new ClienteEditView(null,true);
        ce.setRegistroActual(list.get(masterTable.getSelectedRow()));
        ce.setVisible(true);
        if (ce.isConfirmarCliente()){
            Guardar.doClick();
        }
        else {
            Actualizar.doClick();
        }
    }//GEN-LAST:event_EditarCliente_BotonActionPerformed

    

           
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Actualizar;
    private javax.swing.JButton EditarCliente_Boton;
    private javax.swing.JButton EliminarCliente_Boton;
    private javax.swing.JButton EliminarDir_Boton;
    private javax.swing.JButton Guardar;
    private javax.swing.JButton IngresarCliente_Boton;
    private javax.swing.JButton IngresarDir_Boton;
    private javax.swing.JScrollPane detailScrollPane;
    private javax.swing.JTable detailTable;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private java.util.List<py.com.sysvent.bean.Cliente> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.persistence.Query query;
    // End of variables declaration//GEN-END:variables
    public static void main(final String[] args) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClienteView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new ClienteView());
                //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
                frame.setTitle(args[0]);
            }
        });
    }
}
